import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    TABLE,
    PAGINATION_OPTIONS,
    FIXED_COLUMN_WIDTH,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    DATETIME_FORMAT
} from '../constants';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {partOrderPlanStatus, currency} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {PERMISSIONS} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {injectIntl} from './intl';
import {abandonPartOrderPlan, submitPartOrderPlan} from './api';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
        };
    }
    handleSubmitClick = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        submitPartOrderPlan(id, {rowVersion: record.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.refreshListData();
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonPartOrderPlan(id, {rowVersion: record.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.refreshListData();
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total, sortedColumnKey, sortedOrder} = this.props;
        const paginationInfo = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };

        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.brandCode',
                defaultMessage: '品牌编号'
            }),
            dataIndex: 'brandCode',
            sorter: true,
            sortOrder: sortedColumnKey === 'brandCode' && sortedOrder,
        }];

        if(!this.props.initDate.isDealerUser)
            columns.push({
                title: formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
                sorter: true,
                sortOrder: sortedColumnKey === 'dealerCode' && sortedOrder,
            });

        columns.push({
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: sortedColumnKey === 'code' && sortedOrder,
            render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTimeYear',
                defaultMessage: '提报年份'
            }),
            dataIndex: 'createTimeYear',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTimeMonth',
                defaultMessage: '提报月份'
            }),
            dataIndex: 'createTimeMonth',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.orderPlanYear',
                defaultMessage: '计划年份'
            }),
            dataIndex: 'orderPlanYear',
            sorter: true,
            sortOrder: sortedColumnKey === 'orderPlanYear' && sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.orderPlanMonth',
                defaultMessage: '计划月份'
            }),
            dataIndex: 'orderPlanMonth',
            sorter: true,
            sortOrder: sortedColumnKey === 'orderPlanMonth' && sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            sorter: true,
            sortOrder: sortedColumnKey === 'status' && sortedOrder,
            render: text => conventEnumValueToString(partOrderPlanStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.n2OrderVarietySum',
                defaultMessage: 'N+2需求计划品种数'
            }),
            dataIndex: 'n2OrderVarietySum',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.n2OrderPlanQty',
                defaultMessage: 'N+2需求计划数量'
            }),
            dataIndex: 'n2OrderPlanQty',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalFee',
                defaultMessage: 'N+2月订购总金额'
            }),
            dataIndex: 'totalFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '创建日期'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [];
                if(this.props.initDate.isDealerUser)
                    menus.push({
                        id: PERMISSIONS.submit,
                        children: (
                            <WrappedPopconfirm
                                id={r.id}
                                key="submit"
                                title={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                okText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.confirm',
                                    defaultMessage: '确认'
                                })}
                                cancelText={this.props.intl.formatMessage({
                                    id: 'detail.popconfirm.cancel',
                                    defaultMessage: '取消'
                                })}
                                onConfirm={this.handleSubmitClick}>
                                <a>{
                                    formatMessage({
                                        id: 'detail.popconfirm.submit',
                                        defaultMessage: '提交'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permission, PERMISSIONS.submit) && hasPermissions(r.options, PERMISSIONS.submit))
                    }, {
                        id: PERMISSIONS.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(this.props.permission, PERMISSIONS.update) && hasPermissions(r.options, PERMISSIONS.update))
                    }, {
                        id: PERMISSIONS.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permission, PERMISSIONS.abandon) && hasPermissions(r.options, PERMISSIONS.abandon))
                    });
                else
                    menus.push({
                        id: PERMISSIONS.approve,
                        children: (
                            <Link key="approve" to={routes.approve.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.approve',
                                    defaultMessage: '审核'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(this.props.permission, PERMISSIONS.approve) && hasPermissions(r.options, PERMISSIONS.approve))
                    });
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={paginationInfo}
                    rowKey="id"
                    locale={locale}
                    {...TABLE} >
                </Table>
            </div>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    initDate: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permission: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getInitDate = selectorFactory(['page', 'domainData', 'initData']);
const mapStateToProps = state => ({
    data: getData(state),
    initDate: getInitDate(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permission: getPermissions(state),
});
const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));

